<template>
  <div class="areapicker-wrap" v-if="areaList.length">
    <w-select v-model="province" :options="aProvince" @on-select="onSelectProvince"></w-select>
    <w-select v-model="city" :options="aCity" @on-select="onSelectCity"></w-select>
    <w-select v-model="county" :options="aCounty" @on-select="onSelectCounty"></w-select>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    value: ''
  },
  data() {
    return {
      aProvince: [],
      aCity: [],
      aCounty: [],
      province: '',
      city: '',
      county: '',
      checkedArea: []
    }
  },
  created() {
    this.$store.dispatch('fetchAllArea', () => {
      if (!this.areaList || this.areaList.length == 0) return
      this.aProvince = this.areaList.map(item => {
        return {
          value: item.id,
          label: item.areaName
        }
      })
      this.$nextTick(() => {
        if (this.value) {
          this._setSelectNameByValue(this.value)
        }
      })
    })
  },
  methods: {
    // 点击省份选择框
    onSelectProvince(val) {
      if (!val) return
      this.checkedArea[0] = val
      this.province = val
      this._setCityList()
    },
    // 点击城市选择器
    onSelectCity(val) {
      if (!val) return
      this.checkedArea[1] = val
      this.city = val
      this._setCountyList()
    },
    // 点击地级市选择器，确定选择id
    onSelectCounty(val) {
      if (!val) return
      this.checkedArea[2] = val
      this.county = val
      this.$emit('input', this.checkedArea.join(','))
    },
    // 设置城市的数据
    _setCityList() {
      this.city = ''
      this.county = ''
      const cityList = this.areaList.filter(item => {
        return item.id == this.province
      })
      this.aCity = cityList[0].childs.map(item => {
        return {
          value: item.id,
          label: item.areaName,
          childs: item.childs
        }
      })
    },
    // 设置县市区的数据
    _setCountyList() {
      this.county = ''
      const countyList = this.aCity.filter(item => {
        return item.value == this.city
      })
      this.aCounty = countyList[0].childs.map(item => {
        return {
          value: item.id,
          label: item.areaName
        }
      })
    },
    // 如果一开始传入值，则显示
    _setSelectNameByValue(value) {
      if (!value) return
      const list = value.split(',')
      this.onSelectProvince(list[0])
      this.onSelectCity(list[1])
      this.onSelectCounty(list[2])
    }
  },
  computed: {
    ...mapGetters(['areaList'])
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal != oldVal) {
        this._setSelectNameByValue(newVal)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.areapicker-wrap {
  display: inline-block;
  .select-wrap {
    display: inline-block;
  }
}
</style>